# coding:utf-8
import cv2
from PIL import Image
from scipy import ndimage
from skimage.color import rgb2gray
from skimage.feature import corner_harris, corner_peaks
from skimage.exposure import equalize_hist
import skimage.io as io
from skimage import feature as skft
from numpy import *
from mahotas.features import surf
import matplotlib.pyplot as plt
import pandas as pd
from pylab import *
from scipy.ndimage import filters

class RL(object):
    def __init__(self,img):
        self.im = img
        self.img = self.img_
    @property
    def img_(self):
        im = cv2.imread(self.im)
        return im

    def yolo(self):
        gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
        # ret, binary = cv2.threshold(gray, 254,255, cv2.THRESH_BINARY)
        # cv2.imshow('threasold',binary)
        th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        # th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
        cv2.imshow('th2',th2)
        binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        i = 0
        maxarea = -1
        roci = (0,0,0,0)
        # for contour in contours:
        #     x, y, w, h = cv2.boundingRect(contour)
        #     if (not abs(h-y) < 5) and not (abs(h-y) > 50):  # 比例>0.2
        #     # if ((not abs(w-x) < 20) and (not abs(w-x) > 50)) and ((not abs(h-y) < 10 or not abs(h-y) > 30)): # 比例>0.2
        #     # cv2.drawContours(img_1,contours,i,(0,255,0))
        #     # if ((not abs(w-x) < 10) and (not abs(w-x) > 40)) and ((not abs(h-y) < 10) and (not abs(h-y) > 40)):
        #     #     print(h, y)
        #     #     print('w',w)
        #     # #     i+=1
        #     #     cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        #         tarea = w*h
        #         if maxarea < tarea:
        #             maxarea = tarea
        #             roci = (x,y,w,h)
            # print(i)
        print("矩形宽，高", roci[2], '    ', roci[3])
        img__ = self.img[roci[1]:roci[1]+roci[3],roci[0]:roci[0]+roci[2]]
        # cv2.rectangle(self.img, (roci[0], roci[1]), (roci[0] + roci[2], roci[1] + roci[3]), (0, 255, 0), 2)
        # cv2.imshow('sfsfs',img__)
        # cv2.imshow('sfsw',self.img)
        # cv2.imwrite("b3.jpg",img__)
        return img__

    def cannyy(self):
        kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 锐化
        gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)

        dst = cv2.filter2D(self.img,-1,kernel=kernel)
        canny = cv2.Canny(gray,50,150)
        # surf = cv2.xfeatures2d_SURF()
        # 找到关键点和描述符
        # gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)

        # detector = cv2.xf
        # keypoints = detector.detect(self.img, None)
        # key_query, desc_query = surf.detectAndCompute(self.img)
        # 把特征点标记到图片上
        # img = cv2.drawKeypoints(self.img, keypoints, self.img)
        cv2.imshow("img", dst)
        cv2.imshow("imgs",canny)
        # cv2.imshow("imgs",dst)

    def integral(self):
        # print(self.img)
        img = cv2.cvtColor(self.img,cv2.COLOR_RGB2GRAY)
        # # cv2.imshow('imgsfs',img)
        # # integ = cv2.integral(self.img,cv2.CV_32F)
        # # print(img)
        ret, binary = cv2.threshold(self.img, 254, 255, cv2.THRESH_BINARY)
        # print(binary)
        print(img)
        img_hist = cv2.calcHist([binary], [1], None, [256], [0, 256])
        print(img_hist)
        # cv2.imshow("img", self.img)
        # cv2.imshow("imgs",binary)

        plt.subplot(111), plt.plot(img_hist)
        plt.show()
        print('sfs')
    def thresh(self):
        img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        gray = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
        #
        # gray = cv2.cvtColor(gray, cv2.COLOR_RGB2GRAY)
        # th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
        # th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
        # canny = cv2.Canny(gray,50,150)
        # # th3 = cv2.fastNlMeansDenoisingColored(th3, None, 10, 10, 7, 21)
        # binary, contours, hierarchy = cv2.findContours(th3, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        #
        # cv2.imshow("img", self.img)
        # cv2.imshow('th2',canny)
        # cv2.drawContours(self.img, contours, -1, (0, 0, 255), 3)

        cv2.imshow('th3',gray)

    def threrg(self):
        ijmg:np.ndarray = self.yolo()
        # cv2.imshow('ori ocr',img)
        ijmg = cv2.cvtColor(ijmg, cv2.COLOR_BGR2GRAY)
        iimg = ijmg.copy()
        cv2.imshow('ori ocr',iimg)
        print(iimg, '\n', type(iimg))

        # def go(a):
        #     for i in range(len(a)):
        #         if a[i] < 5:
        #             a[i] = 0
        #         elif a[i] > 240:
        #             a[i] = 255
        #     return a
        # np.apply_along_axis(go,1,iimg)
        # print(iimg, '\n', type(iimg))

        # img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        # img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 4, 21)
        img = cv2.GaussianBlur(iimg, (5,5), 0)
        img =cv2.medianBlur(img,7)
        cv2.imshow('jppp',img)
        # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
        # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, th2 = cv2.threshold(img, 60,255, cv2.THRESH_BINARY)

        # th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        # th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
        # th2 = cv2.dilate(th2,kernel)
        # th3 = cv2.erode(th3,kernel)
        # th2 = cv2.morphologyEx(th2, cv2.MORPH_OPEN, kernel)
        # th2 = cv2.fil(th2,kernel)
        canny = cv2.Canny(th2,0,20)

        binary, contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(canny, contours, -1, (0, 0, 255), 3)


        # # th3 = cv2.fastNlMeansDenoisingColored(th3, None, 10, 10, 7, 21)
        # binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # print(contours[0])
        # print(canny.shape)
        # print(ijmg.shape)
        canny = cv2.add(ijmg,canny)
        # canny = cv2.Canny(canny,0,20)
        # img_hist = cv2.calcHist([canny], [0], None, [256], [0, 256])

        # print('img_hist', np.array([img_hist[-1]]))
        cv2.imshow("img", th2)
        cv2.imshow('th2',canny)
        # cv2.imwrite('th2C.jpg',th2)
        # cv2.drawContours(self.img, contours, -1, (0, 0, 255), 3)
        # cv2.imshow('canny',canny)
        # cv2.imshow('th3',th3)
        # cv2.imwrite('th3C.jpg',th3)
        # cv2.imshow('contr',self.img)
    def show_corners(self,corners, image):
        import numpy as np
        import matplotlib.pyplot as plt
        fig = plt.figure()
        plt.gray()
        plt.imshow(image)
        y_corner, x_corner = zip(*corners)
        plt.plot(x_corner, y_corner, 'or')
        plt.xlim(0, image.shape[1])
        plt.ylim(image.shape[0], 0)
        fig.set_size_inches(np.array(fig.get_size_inches()) * 1.5)
        plt.show()
    def hpf(self):
        kernel_3x3 = np.array([[-1, -1, -1],
                               [-1, 8, -1],
                               [-1, -1, -1]])

        kernel_5x5 = np.array([[-1, -1, -1, -1, -1],
                               [-1, 1, 2, 1, -1],
                               [-1, 2, 4, 2, -1],
                               [-1, 1, 2, 1, -1],
                               [-1, -1, -1, -1, -1]])

        img = io.imread(self.im, as_grey=True)

        k3 = ndimage.convolve(img, kernel_3x3)
        k5 = ndimage.convolve(img, kernel_5x5)

        # cv2.GaussianBlur 高斯滤波，(17,17)为核大小，包含宽度和高度的二元组。
        blurred = cv2.GaussianBlur(img, (17, 17), 0)
        g_hpf = img - blurred
        cv2.imshow("img", img)
        cv2.imshow("3x3", k3)
        cv2.imshow("5x5", k5)
        cv2.imshow('blurred', blurred)
        cv2.imshow("g_hpf", g_hpf)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    def thrsrect(self):
        img = cv2.GaussianBlur(self.img, (5, 5), 0)
        img = cv2.medianBlur(img, 7)
        gray_lap = cv2.Laplacian(self.img,cv2.CV_16S,ksize=3)
        dst = cv2.convertScaleAbs(gray_lap)
        dst = cv2.add(self.img,dst)
        cv2.imshow('lalp',dst)
        cv2.imshow('pre_la',gray_lap)
        cv2.imshow('ori',self.img)

    def showtime(self):

        _, img = cv2.threshold(self.img, 254, 255, cv2.THRESH_BINARY)
        img_hist = cv2.calcHist(img, [0], None, [256], [0, 256])
        print(img_hist, '\n')
        return img_hist
    def ju(self):
        gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
        # ret, binary = cv2.threshold(gray, 254,255, cv2.THRESH_BINARY)
        # cv2.imshow('threasold',binary)
        th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        # th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 2)
        cv2.imshow('th2', th2)
        binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # gray = cv2.cvtColor(self.img,cv2.COLOR_BGR2GRAY)
        # blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        # thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1]
        # binary, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        for c in contours:
            M = cv2.moments(c)
            print(M, type(M))
            cX = int(M['m10']/M['m00'])
            cY = int(M['m01']/M['m00'])

            cv2.drawContours(self.img, [c], -1, (0, 255, 0), 2)
            cv2.circle(self.img, (cX, cY), 7, (255, 255, 255), -1)

        cv2.drawContours(self.img, contours, -1, (0, 0, 255), 3)
        # cv2.imshow('thresh',thresh)
        cv2.imshow('img',self.img)
    def do_ju(self):
        img = cv2.GaussianBlur(self.img, (5, 5), 0)
        img = cv2.medianBlur(img, 7)
        canny = cv2.Canny(img, 0, 20)
        binary, contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        # cv2.drawContours(self.img, contours, -1, (0, 0, 255), 3)

        for c in contours:
            x,y,w,h= cv2.boundingRect(c)
            if (not abs(h-y) < 5) and not (abs(h-y) > 50):  # 比例>0.2
                print('-', c, '-')
                print(x, y, w, h)
                M = cv2.moments(c)
                hu = cv2.HuMoments(M)
                print(hu)
                print(M, type(M))
                cX = int(M['m10'] / M['m00']) #对象的重心
                cY = int(M['m01'] / M['m00'])

                cv2.drawContours(self.img, [c], -1, (0, 255, 0), 2)
                cv2.circle(self.img, (cX, cY), 7, (255, 255, 255), -1)

        cv2.imshow('can',canny)
        cv2.imshow('img',self.img)
        return canny
    def holf(self):
        gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
        th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        _, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        i = 0
        maxarea = -1
        roci = (0, 0, 0, 0)
        cv2.drawContours(self.img, contours, -1, (255,0,0), 2)
        cv2.imshow('sfs',self.img)
        tc = None
        for contour in contours:
            # M = cv2.moments(contour)
            # hu = cv2.HuMoments(M)
            # print(hu)
            # print(M, type(M))
            x, y, w, h = cv2.boundingRect(contour)
            if (not abs(h - y) < 5) and not (abs(h - y) > 50):  # 比例>0.2
                # cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                tarea = w * h
                if maxarea < tarea:
                    maxarea = tarea
                    roci = (x, y, w, h)
                    tc = contour
        # print("矩形宽，高", roci[2], '    ', roci[3])
        M = cv2.moments(tc)
        hu = cv2.HuMoments(M)
        # print(hu,type(hu))
        # print(M, type(M))

        img__ = gray[roci[1]:roci[1] + roci[3], roci[0]:roci[0] + roci[2]]
        img__ = cv2.resize(img__, dsize=(123, 126))

        # cv2.imshow('croped', img__)

        # img = cv2.GaussianBlur(img__, (3, 3), 0)
        #
        # img = cv2.medianBlur(img, 3)
        # # canny = cv2.Canny(img,0,20)

        th2 = cv2.adaptiveThreshold(img__, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        M = cv2.moments(img__)
        hu = cv2.HuMoments(M)
        print(type(hu),hu,'-jjj-')
        cv2.imshow('th2',th2)
        # fixme:对二值作处理
        # cv2.imshow('canny',canny)
        binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(img__, contours, -1, (255,0,0), 2)


        # for cnt in range(len(contours)):
        #     # 提取与绘制轮廓
        #     cv2.drawContours(canny, contours, cnt, (0, 255, 0), 1)

            # # 轮廓逼近
            # epsilon = 0.01 * cv2.arcLength(contours[cnt], True)
            # approx = cv2.approxPolyDP(contours[cnt], epsilon, True)
            #
            # # 分析几何形状
            # corners = len(approx)
            # shape_type = ""
        # cv2.imshow('th2',th2)
        # cv2.imshow('img',img__)
        # cv2.imshow('draw_canny',canny)

        return img__
    def jisuan(self,img1,img2):
        img1 = img1
        img2 = img2
        def read(img):
            img = cv2.imread(img)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
            _, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            i = 0
            maxarea = -1
            roci = (0, 0, 0, 0)
            for contour in contours:
                x, y, w, h = cv2.boundingRect(contour)
                if (not abs(h - y) < 5) and not (abs(h - y) > 50):  # 比例>0.2
                    # cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                    tarea = w * h
                    if maxarea < tarea:
                        maxarea = tarea
                        roci = (x, y, w, h)
            # print("矩形宽，高", roci[2], '    ', roci[3])

            img__ = gray[roci[1]:roci[1] + roci[3], roci[0]:roci[0] + roci[2]]
            img__ = cv2.resize(img__, dsize=(123, 126))
            M = cv2.moments(img__)
            hu = cv2.HuMoments(M)
            return hu.tolist()
        sa = read(img1)
        ta = read(img2)
        dbr = 0
        dsigmaST = 0
        dsigmas = 0
        dsigmat = 0
        for i in range(7):
            temp = sa[i][0] * ta[i][0]
            dsigmaST+=temp
            dsigmas+=pow(sa[i][0],2)
            dsigmat+=pow(ta[i][0],2)
        dbr = dsigmaST/(math.sqrt(dsigmas)*math.sqrt(dsigmat))
        print(dbr)
        return dbr
def show_corners(corners, image):
    import numpy as np
    import matplotlib.pyplot as plt
    fig = plt.figure()
    plt.gray()
    plt.imshow(image)
    y_corner, x_corner = zip(*corners)
    plt.plot(x_corner, y_corner, 'or')
    plt.xlim(0, image.shape[1])
    plt.ylim(image.shape[0], 0)
    fig.set_size_inches(np.array(fig.get_size_inches()) * 1.5)
    plt.show()

def shows(img):
    img = cv2.imread(img)
    t_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    lbp = skft.local_binary_pattern(t_img, 16, 1, 'default')
    cv2.imshow("sfs",img)
    cv2.imshow("img",lbp)
    cv2.waitKey(0)


def do_crop(img):
    img = cv2.imread(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
    _,contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    i = 0
    maxarea = -1
    roci = (0, 0, 0, 0)
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if (not abs(h - y) < 5) and not (abs(h - y) > 50):  # 比例>0.2
            # cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            tarea = w * h
            if maxarea < tarea:
                maxarea = tarea
                roci = (x, y, w, h)
    print("矩形宽，高", roci[2], '    ', roci[3])
    img__ = gray[roci[1]:roci[1] + roci[3], roci[0]:roci[0] + roci[2]]
    img__ = cv2.resize(img__,dsize=(123,126))
    cv2.imshow('croped',img__)
    return img__


def sobel_extract(img):
    im = do_crop(img)
    # soble 导数滤波器  使用 Sobel 滤波器来计算 x 和 y 的方向导数，
    imx = zeros(im.shape)
    filters.sobel(im, 1, imx)
    #
    imy = zeros(im.shape)
    filters.sobel(im, 0, imy)

    magnitude = sqrt(imx ** 2 + imy ** 2)

    # print(magnitude)
    def deal_with(a):
        for i in range(len(a)):
            if a[i] < 50:
                a[i] = 0
            elif a[i] > 200:
                a[i] = 255
        return a

    a = np.apply_along_axis(deal_with, 1, magnitude)
    result = contour(magnitude, origin='image')
    cv2.imshow('magnitude',magnitude)
    _,th2 = cv2.threshold(magnitude,60,255,cv2.THRESH_BINARY)
    cv2.imshow('magnitude',th2)
    print(th2)
    # figure()
    # hist(magnitude.flatten(), 128)
    # show()
    # binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # cv2.drawContours(im, contours, -1, (255, 0, 0), 2)
    cv2.imshow('im',im)


# def oin():
#     from sklearn import svm, datasets
#
#     iris = datasets.load_iris()
#     x = iris.data[:, :2]  # 2D graph,2features
#     y = iris.target
#     print(x[0])
if __name__ == "__main__":
    img = r"C:\Users\Administrator\Desktop\origin\1538966507089.jpg"
    img = r'C:\Users\Administrator\Desktop\ccc.jpg'
    # img = r'C:\Users\Administrator\Desktop\pssss\CC\1538967246162.jpg'
    # img = r'C:\Users\Administrator\Desktop\pssss\DD\1538967473497.jpg'
    img2 = r'C:\Users\Administrator\Desktop\ceshi\11\d3.jpg'
    img = r'C:\Users\Administrator\Desktop\59\1539134451814.jpg'
    # img1 = r'C:\Users\Administrator\Desktop\photobase\FOUR\D.jpg'
    img1 = r'C:\Users\Administrator\Desktop\photobase\FOUR\D.jpg'
    # img11 = r'C:\Users\Administrator\Desktop\photobase\THREE\C.jpg'
    # img = r'C:\Users\Administrator\Desktop\canny\a1.jpg'
    img11 = r'C:\Users\Administrator\Desktop\photobase\ONE\A.jpg'
    # img11 = r'C:\Users\Administrator\Desktop\photobase\TWO\B.jpg'
    img11 = r'C:\Users\Administrator\Desktop\photobase2\THREE\C.jpg'
    # img11 = r'C:\Users\Administrator\Desktop\photobase\FIVE\E.jpg'
    # img = r'C:\Users\Administrator\Desktop\ceshi\11\d3.jpg'
    # img = r'C:\Users\Administrator\Desktop\pssss\CC\1538967250924.jpg'
    # img = r'C:\Users\Administrator\Desktop\bugg\tmp0.jpg'
    # img = r'C:\Users\Administrator\Desktop\SFSFS.jpg'
    rc = RL(img)
    # rt = RL(imga)

    # mandrill = io.imread(img)
    # mandrill = equalize_hist(rgb2gray(mandrill))
    # corners = corner_peaks(corner_harris(mandrill), min_distance=5)
    # show_corners(corners, mandrill)
    # do_crop(img)
    # img = cv2.imread(img)
    # print(img.shape)
    # rc.thresh()
    # oin()
    # sobel_extract(img)
    # rc.yolo()
    # print(rc.jisuan(img1,img2) > rc.jisuan(img11,img2))
    # rc.integr。al()
    # rc.cannyy()
    img = r"C:\Users\Administrator\Desktop\dbf5adc8-1041-4563-9b2e-2865e7303f2d_0.jpg"
    img = r"C:\Users\Administrator\Desktop\eb7dc94a-19eb-4993-bee5-96aa5ebc8ee5_0.jpg"
    img = r"C:\Users\Administrator\Desktop\50839179-810c-4f82-b035-5e26d8458d30_0"
    do_crop(img)
    # rc.threrg()
    # rc.do_ju()
    # rc.hpf()
    # rc.holf()
    # rc.thrsrect()
    # c = rc.showtime()
    # t = rt.showtime()
    # distance = np.linalg.norm(c-t, axis=None)
    cv2.waitKey(0)
    cv2.destroyWindow()


